import {defineStore} from 'pinia'
import axios from "axios";
import {nanoid} from "nanoid";

//选项式写法

// export const useTalkStore = defineStore('talk', {
//   //state要写成一个函数 ===真正存数据的地方
//   actions: {
//     getATalk() {
//       axios.get('https://api.uomg.com/api/rand.qinghua?format=json').then(res => {
//         //这个写法是连续解构赋值加重命名
//         let {data:{content:title}} = res
//         console.log(res.data)
//         //把字符串包装成对象
//         let obj = {id: nanoid(),title }
//         this.talkList.unshift(obj)
//       })
//     }
//   },
//   state() {
//     return {
//       // talkList: localStorage.getItem('talkList') //这样是错的,因为他是字符串
//       talkList: JSON.parse(localStorage.getItem('talkList') as string)  || [] //这样是错的,因为他是字符串
//     }
//   }
// })
import { reactive } from "vue";

export const useTalkStore = defineStore('talk', () => {

  //talkList就是state
  const talkList = reactive(JSON.parse(localStorage.getItem('talkList') as string)  || [])

  //getATalk函数 ====> 相当于action
    function getATalk() {
      axios.get('https://api.uomg.com/api/rand.qinghua?format=json').then(res => {
        //这个写法是连续解构赋值加重命名
        let {data:{content:title}} = res
        console.log(res.data)
        //把字符串包装成对象
        let obj = {id: nanoid(),title }
        talkList.unshift(obj)
      })
    }
    return { talkList,getATalk }
})